<?php

namespace app\admin\controller\vppz;

use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Session;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Oldpeople extends Base
{

    /**
     * Service模型对象
     * @var \app\admin\model\vppz\Qxzl
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vppz\Oldpeople;
        $this->infomodel = new \app\admin\model\vppz\MedicalInformation;
        $this->kangyangmodel = new \app\admin\model\vppz\Kangyang;
        $this->view->assign('genders',[
            1=>'男',
            2=>'女',
            3=>'其他'
        ]);
        $this->view->assign('blood_types',['A','B','AB','O','其他']);
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $ids = input('ids',0);
        $admin = Session::get("admin");
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $listmodel = $this->model;
            $searchWhere =[];
            if($admin['is_pingtai'] != 1){
                $hospital = $this->kangyangmodel->where(['admin_id'=>$admin['id']])->find();
                if(empty($hospital) === FALSE){
                    $searchWhere = ['center_id'=>$hospital->id];
                    $listmodel = $listmodel->where($searchWhere);
                }else{
                    $searchWhere = ['center_id'=>0];
                    $listmodel = $listmodel->where($searchWhere);
                }
            }
            $list = $listmodel->where($where)
                    ->with(['kangyang'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            foreach ($list as $row) {

                $row->getRelation('kangyang')->visible(['title']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        $this->assignconfig('kangyang_id',$ids);

        $this->view->assign('kangyang_id',$ids);

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->modelValidate = true;
            $params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $form = $this->preExcludeFields($params);
            $admin = Session::get("admin");
            $hospital = $this->kangyangmodel->where(['admin_id'=>$admin['id']])->find();
            $result = false;
            try {
                $this->model->startTrans();
                $opera = [];
                $info = $this->model->where(array(
                    'name'=>$form['name'],
                    'idcard'=>$form['idcard']
                ))->find();
                if(empty($info) === FALSE){
                    $this->error('老人信息已经存在');
                }
                $center_id = '';
                if(empty($hospital) === FALSE){
                    $center_id = $hospital->id;
                }else{
                    $center_id = $this->request->get('ids');
                }
                if(empty($center_id)){
                    $this->error('康养中心信息有误');
                }
                //todo 基本信息
                $data = array(
                    'name'=>$form['name'],
                    'idcard'=>$form['idcard'],
                    'mobile'=>$form['mobile'],
                    'avator'=>$form['avator'],
                    'gender'=>$form['gender'],
                    'blood_types'=>$form['blood_types'],
                    'age'=>$form['age'],
                    'birth'=>$form['birth'],
                    'height'=>$form['height'],
                    'weight'=>$form['weight'],
                    'jinji_name'=>$form['jinji_name'],
                    'jinji_mobile'=>$form['jinji_mobile'],
                    'address'=>$form['address'],
                    'content'=>$form['content'],
                    'center_id'=>$center_id
                );
                $oldid = $this->model->insert($data);
                $opera[] = $oldid;
                //todo 添加病例
                $outpatient = [];
                $physical = [];
                $res = [];
                if(empty($form['outpatient']) === FALSE){
                    $outpatient = explode(',',$form['outpatient']);
                    $resdata = array(
                        'type'=>'outpatient',
                        'image'=>json_encode($outpatient),
                        'old_id'=>$oldid,
                        'createtime'=>time(),
                        'updatetime'=>time()
                    );
                    array_push($res,$resdata);
                }
                if(empty($form['physical']) === FALSE){
                    $physical = explode(',',$form['physical']);
                    $resdata = array(
                        'type'=>'physical',
                        'image'=>json_encode($physical),
                        'old_id'=>$oldid,
                        'createtime'=>time(),
                        'updatetime'=>time()
                    );
                    array_push($res,$resdata);
                }
                if(empty($res) === FALSE){
                    if(count($res) > 1){
                        $opera[] = $this->infomodel->insertAll($res);
                    }else{
                        $opera[] = $this->infomodel->insert($res[0]);
                    }
                }
                if(\Tools::checkArrayResult($opera)){
                    $this->model->commit();
                    $this->success();
                }else{
                    $this->model->rollback();
                    $this->error('失败');
                }
            } catch (ValidateException|PDOException|Exception $e) {
                $this->error($e->getMessage());
            }
        }

        $admin = Session::get("admin");
        $this->assign('admin',$admin);
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $images = $this->infomodel->where([
                'old_id'=>$ids
            ])->select();
            $dataimage = [];
            if(empty($images) === FALSE){
                foreach ($images as &$v) {
                    if ($v['type'] == 'physical') {
                        $dataimage['physical'] = implode(',', json_decode($v->image, true));
                    }
                    if ($v['type'] == 'outpatient') {
                        $dataimage['outpatient'] = implode(',', json_decode($v->image, true));
                    }
                }
            }
            $this->view->assign('images', $dataimage);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $this->modelValidate = true;
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $form = $this->preExcludeFields($params);
        $result = false;

        try {
            $this->model->startTrans();
            $admin = Session::get("admin");
            $hospital = $this->kangyangmodel->where(['admin_id'=>$admin['id']])->find();
            $center_id = '';
            if(empty($hospital) === FALSE){
                $center_id = $hospital->id;
            }
            if(empty($center_id)){
                $this->error('康养中心信息有误');
            }
            $opera = [];
            //todo 基本信息
                $data = array(
                    'mobile'=>$form['mobile'],
                    'avator'=>$form['avator'],
                    'gender'=>$form['gender'],
                    'blood_types'=>$form['blood_types'],
                    'age'=>$form['age'],
                    'birth'=>$form['birth'],
                    'height'=>$form['height'],
                    'weight'=>$form['weight'],
                    'jinji_name'=>$form['jinji_name'],
                    'jinji_mobile'=>$form['jinji_mobile'],
                    'address'=>$form['address'],
                    'content'=>$form['content'],
                    'center_id'=>$center_id
                );
                $opera[] = $this->model->where(['id'=>$ids])->update($data);
                //todo 添加病例
                $outpatient = [];
                $physical = [];
                $res = [];
                $old_image = $this->infomodel->where([
                    'old_id'=>$ids
                ])->find();
                if(empty($old_image) === FALSE){
                    $opera[] = $this->infomodel->where([
                        'old_id'=>$ids
                    ])->delete();
                }
                if(empty($form['outpatient']) === FALSE){
                    $outpatient = explode(',',$form['outpatient']);
                    $resdata = array(
                        'type'=>'outpatient',
                        'image'=>json_encode($outpatient),
                        'old_id'=>$ids,
                        'createtime'=>time(),
                        'updatetime'=>time()
                    );
                    array_push($res,$resdata);
                }
                if(empty($form['physical']) === FALSE){
                    $physical = explode(',',$form['physical']);
                    $resdata = array(
                        'type'=>'physical',
                        'image'=>json_encode($physical),
                        'old_id'=>$ids,
                        'createtime'=>time(),
                        'updatetime'=>time()
                    );
                    array_push($res,$resdata);
                }
                if(empty($res) === FALSE){
                    if(count($res) > 1){
                        $opera[] = $this->infomodel->insertAll($res);
                    }else{
                        $opera[] = $this->infomodel->insert($res[0]);
                    }
                }
                if(\Tools::checkArrayResult($opera)){
                    $this->model->commit();
                    $this->success();
                }else{
                    $this->model->rollback();
                    $this->error('失败');
                }
        } catch (ValidateException|PDOException|Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success();

    }
    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import()
    {
        // 临时调整内存限制（根据需求设置，建议 512M 或 1G，用完自动恢复默认）
        ini_set('memory_limit', '512M');
        // 同时建议调整最大执行时间（避免大文件处理超时）
        ini_set('max_execution_time', 300); // 300秒=5分钟

        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $file = str_replace('https://dida.qcsheji.cn/','',$file);
        $file = str_replace('https://peizhen.banyetang.cn/','',$file);
        $filePath = ROOT_PATH  . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
//            $reader = IOFactory::createReader('Xlsx');
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);

        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }
        //加载文件
        $insert = [];
        try {
            $reader->setReadDataOnly(true);         // 仅读数据（核心优化，减少80%内存）
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            $admin = Session::get("admin");
            $hospital = $this->kangyangmodel->where(['admin_id'=>$admin['id']])->find();
            $center_id = '';
            $center_name = '';
            if(empty($hospital) === FALSE){
                $center_id = $hospital->id;
                $center_name = $hospital->title;
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $info = $this->model->where(array(
                        'name'=>$row['name'],
                        'idcard'=>$row['idcard']
                    ))->find();
                    if(empty($info)) {
                        if(empty($center_id)){
                            //获取养老中心
                            $kangyang = $this->kangyangmodel->where(['title'=>$row['center_name']])->find();
                            if(empty($kangyang) === FALSE){
                                $center_id = $kangyang->id;
                                $center_name = $kangyang->title;
                            }else{
                                if(empty($center_id)){
                                    continue;
                                }
                            }

                        }
                        $row['center_id'] = $center_id;
                        $row['center_name'] = $center_name;
                        $insert[] = $row;
                    }
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }
}
